<?php
// 应用公共文件

if (!function_exists('get_tree_value')) {
    /**
     * 获取树状结构数据
     * @param array $data
     * @param int|string $value
     * @return array
     * @Author joey
     * @date 2024/2/24 14:06
     */
    function get_tree_value(array $data, $value)
    {
        static $childrenValue = [];
        foreach ($data as &$item) {
            if ($item['value'] == $value) {
                $childrenValue[] = $item['value'];
                if ($item['pid']) {
                    $value = $item['pid'];
                    unset($item);
                    return get_tree_value($data, $value);
                }
            }
        }
        return $childrenValue;
    }
}

if (!function_exists('get_tree_children')) {
    /**
     * tree 子菜单
     * @param array $data 数据
     * @param string $childrenname 子数据名
     * @param string $keyName 数据key名
     * @param string $pidName 数据上级key名
     * @param boolean $getlvs 是否获取三级菜单
     * @return array
     * @Author joey
     * @date 2024/2/24 14:06
     */
    function get_tree_children(array $data, string $childrenname = 'children', string $keyName = 'id', string $pidName = 'pid', $getlvs = true)
    {
        $list = array();
        foreach ($data as $value) {
            $list[$value[$keyName]] = $value;
        }
        // static $tree = array(); //格式化好的树
        $tree = array(); //格式化好的树
        foreach ($list as $item) {
            if (isset($list[$item[$pidName]])) {
                if($getlvs){
                    $list[$item[$pidName]][$childrenname][] = &$list[$item[$keyName]];
                }else{
                    if(isset($list[$item[$pidName]][$pidName])&&$list[$item[$pidName]][$pidName]>0){
                        continue;
                    }else{
                        $list[$item[$pidName]][$childrenname][] = &$list[$item[$keyName]];
                    }
                }
            } else {
                $tree[] = &$list[$item[$keyName]];
            }
        }
        return $tree;
    }
}

if (!function_exists('get_tree_list')) {
    function get_tree_list(array $data, string $childrenname = 'children', string $keyName = 'id', string $pidName = 'pid', $pid = 0)
    {
        $tree = [];

        foreach ($data as $item) {
            if ($item[$pidName] != $pid) continue;
            $children = get_tree_list($data, $childrenname, $keyName, $pidName, $item[$keyName]);
            if ($children) $item[$childrenname] = $children;
            $tree [] = $item;
        }
        return $tree;
    }
}